package com.waner.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waner.reggie.common.CustomException;
import com.waner.reggie.common.R;
import com.waner.reggie.entity.Category;
import com.waner.reggie.entity.Dish;
import com.waner.reggie.entity.Setmeal;
import com.waner.reggie.mapper.CategoryMapper;
import com.waner.reggie.service.CategoryService;
import com.waner.reggie.service.DishService;
import com.waner.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 自定义的根据id删除分类
     * @param id
     * @return
     */
    @Override
    public void remove(Long id) {
        // 构造dish条件查询器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);

        // 查询关联了分类的相关dish或者setmeal的数量
        int dish = dishService.count(dishLambdaQueryWrapper);
        if(dish > 0){
            // 关联了菜品，抛出一个业务异常
            throw new CustomException("当前菜品下关联了菜品，无法删除");
        }

        // 构造setmeal条件查询器
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);

        int setmeal = setmealService.count(setmealLambdaQueryWrapper);
        if(setmeal > 0){
            // 关联了套餐，抛出一个业务异常
            throw new CustomException("当前菜品下关联了套餐，无法删除");
        }

        // 如果没有任何关联，则进行删除操作
        categoryService.removeById(id);
    }
}
